<template>
  <BreadcrumbBar
    parent-label="Authority Management"
    child-label="Role Management"
  ></BreadcrumbBar>

  <InputForm>
    <InputItem label="条件查询角色" more-long="500">
      <el-cascader
        style="width: 100%"
        v-model="queryRoleSortId"
        :options="sortTree"
        :props="{ checkStrictly: true }"
        clearable
        placeholder="请选择上级分类（可选）"
        @visible-change="selectVisibleChangeHandler"
        size="large"
      />
    </InputItem>
    <InputItem label="是否为默认角色">
      <el-select
        v-model="queryDefaultRole"
        placeholder="是否默认"
        size="large"
        clearable
      >
        <el-option label="默认" value="0" />
        <el-option label="非默认" value="1" />
      </el-select>
    </InputItem>
    <InputItem label="角色名称">
      <el-input
        v-model="queryRoleName"
        style="width: 100%; height: 100%"
        clearable
        placeholder="角色名称"
      />
    </InputItem>

    <ButtomItem label="操作">
      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="getRolesList"
      >
        查询
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openCreateRoleDialog"
      >
        新建角色
      </el-button>
    </ButtomItem>
  </InputForm>

  <!-- 角色表格 -->
  <TableCard
    operationBarLabel="批量操作用户"
    :show-expand="50"
    :table-max-height="400"
  >
    <template v-slot:operationBar>
      <el-button
        v-once-click
        color="#626aef"
        plain
        size="small"
        @click="updateRolesStatus(multipleSelectionItems, 0)"
      >
        启用
      </el-button>
      <el-button
        v-once-click
        type="info"
        size="small"
        @click="updateRolesStatus(multipleSelectionItems, 1)"
      >
        禁用
      </el-button>
      <el-popconfirm
        title="确认删除"
        placement="right"
        @confirm="deleteRoles(multipleSelectionItems)"
      >
        <template #reference>
          <el-button v-once-click color="#F56C6C" plain size="small">
            删除
          </el-button>
        </template>
      </el-popconfirm>
    </template>

    <template v-slot:table="{ maxHeight }">
      <el-table
        :data="queryRoleList"
        stripe
        style="width: 100%"
        :max-height="maxHeight"
        @selection-change="handleSelectionChange"
        :headerCellStyle="tableHeaderCellStyle"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column property="enable" label="Enable" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.enable === 1" type="danger"> 禁用 </el-tag>
            <el-tag v-if="scope.row.enable === 0" type="success"> 启用 </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="name" label="Name" sortable width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <div style="margin-right: 6px">{{ scope.row.name }}</div>
              <el-icon
                v-if="scope.row.isDefault == 0"
                title="默认用户角色"
                color="#eebe77"
                size="17"
              >
                <InfoFilled />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="realName" label="RealName" width="160" />
        <el-table-column
          property="description"
          label="Description"
          min-width="360"
          show-overflow-tooltip
        />
        <el-table-column label="Sort" width="360" show-overflow-tooltip>
          <template #default="scope">
            {{
              getDescriptionStr(findParentValues(sortTree, scope.row?.sortId))
            }}
          </template>
        </el-table-column>
        <el-table-column
          property="createTime"
          label="CreateTime"
          width="190"
          sortable
        />
        <el-table-column
          property="updateTime"
          label="UpdateTime"
          width="190"
          sortable
        />
        <el-table-column label="操作" width="450" fixed="right">
          <template #default="scope">
            <el-button
              v-once-click
              color="#529b2e"
              plain
              size="small"
              @click="openRoleUsersDialogHandldr(scope.row)"
            >
              角色用户
            </el-button>
            <el-button
              v-once-click
              color="#626aef"
              plain
              size="small"
              @click="openRolePermissionsDialogHandldr(scope.row)"
            >
              设置权限
            </el-button>
            <el-button
              v-once-click
              color="#529b2e"
              plain
              size="small"
              @click="openRoleRoutesDialogHandldr(scope.row)"
            >
              设置路由
            </el-button>
            <el-button
              v-once-click
              type="info"
              size="small"
              v-if="scope.row.enable === 0"
              @click="updateRolesStatus([scope.row.id], 1)"
            >
              禁用
            </el-button>
            <el-button
              v-once-click
              color="#626aef"
              plain
              size="small"
              v-if="scope.row.enable === 1"
              @click="updateRolesStatus([scope.row.id], 0)"
            >
              启用
            </el-button>
            <el-button
              v-once-click
              color="#E6A23C"
              plain
              size="small"
              @click="
                openUpdateRoleDialog(
                  scope.row.id,
                  scope.row.name,
                  scope.row.realName,
                  scope.row.description,
                  scope.row.sortId,
                  scope.row.isDefault
                )
              "
            >
              修改
            </el-button>
            <el-popconfirm
              title="确认删除"
              placement="left"
              @confirm="deleteRoles([scope.row.id])"
            >
              <template #reference>
                <el-button v-once-click color="#F56C6C" plain size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template v-slot:paginationBar>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :background="true"
        :total="total"
        :page-sizes="[20, 30, 40, 50, 60]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageNumChange"
      />
    </template>
  </TableCard>

  <!--  -->
  <!-- 角色创建对话框 -->
  <el-dialog
    v-model="createRoleDialogVisible"
    title="创建角色对话框"
    width="800px"
    draggable
    :before-close="closeRoleDialog"
  >
    <InputForm>
      <InputItem label="角色分类" more-long>
        <el-cascader
          style="width: 100%"
          v-model="tempRoleSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择角色分类"
          @visible-change="selectVisibleChangeHandler"
          size="large"
        />
      </InputItem>
      <InputItem label="角色名称">
        <el-input
          v-model="roleRealName"
          placeholder="请输入角色名称"
          maxlength="20"
          show-word-limit
        />
      </InputItem>
      <InputItem label="是否设置为用户默认角色">
        <el-select v-model="roleIsDefault" size="large">
          <el-option label="非默认" :value="1" />
          <el-option label="默认" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="角色编码" more-long>
        <el-input
          v-model="roleName"
          placeholder="输入角色编码(禁止中文)"
          maxlength="30"
          show-word-limit
        />
      </InputItem>
      <InputItem label="角色描述" more-long>
        <el-input
          v-model="roleDesc"
          placeholder="请输入角色描述"
          maxlength="30"
          show-word-limit
        />
      </InputItem>
    </InputForm>

    <div class="tips">用户注册完成后，自动拥有用户默认角色</div>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closeRoleDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="createDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 角色修改对话框 -->
  <el-dialog
    v-model="updateRoleDialogVisible"
    title="修改角色对话框"
    width="800px"
    draggable
    :before-close="closeRoleDialog"
  >
    <InputForm>
      <InputItem label="角色分类" more-long>
        <el-cascader
          style="width: 100%"
          v-model="tempRoleSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择角色分类"
          @visible-change="selectVisibleChangeHandler"
          size="large"
        />
      </InputItem>
      <InputItem label="角色名称">
        <el-input
          v-model="roleRealName"
          placeholder="请输入角色名称"
          maxlength="20"
          show-word-limit
        />
      </InputItem>
      <InputItem label="是否设置为用户默认角色">
        <el-select v-model="roleIsDefault" size="large">
          <el-option label="非默认" :value="1" />
          <el-option label="默认" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="角色编码" more-long>
        <el-input
          v-model="roleName"
          placeholder="输入角色编码(禁止中文)"
          maxlength="30"
          show-word-limit
        />
      </InputItem>
      <InputItem label="角色描述" more-long>
        <el-input
          v-model="roleDesc"
          placeholder="请输入角色描述"
          maxlength="30"
          show-word-limit
        />
      </InputItem>
    </InputForm>

    <div class="tips">用户注册完成后，自动拥有用户默认角色</div>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closeRoleDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="updateDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 设置角色权限对话框 -->
  <SetRolePermission
    :roleInfo="settingRole"
    :visible="setRolePermissionsDialogVisible"
    @closeDialogHandler="closeRoleDialogHandldr"
  ></SetRolePermission>

  <!--  -->
  <!-- 设置角色路由对话框 -->
  <SetRoleRoutes
    :roleInfo="settingRole"
    :visible="setRoleRoutesDialogVisible"
    @closeDialogHandler="closeRoleDialogHandldr"
  ></SetRoleRoutes>

  <!--  -->
  <!-- 设置角色用户对话框 -->
  <SetRoleUsers
    :roleInfo="settingRole"
    :visible="setRoleUsersDialogVisible"
    @closeDialogHandler="closeRoleDialogHandldr"
  ></SetRoleUsers>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import {
  getRolesListApi,
  setRoleApi,
  deleteRolesApi,
  updateRolesStatusApi,
} from '@/request/api/roles'

import SetRolePermission from './components/SetRolePermission.vue'
import SetRoleRoutes from './components/SetRoleRoutes.vue'
import SetRoleUsers from './components/SetRoleUsers.vue'
import InputForm from '@/components/InputForm/InputForm.vue'
import InputItem from '@/components/InputForm/InputItem.vue'
import ButtomItem from '@/components/InputForm/ButtomItem.vue'
import TableCard from '@/components/TableCard/TableCard.vue'
import BreadcrumbBar from '@/components/BreadcrumbBar/BreadcrumbBar.vue'

const { originData } = storeToRefs(useSortTreeStore())
const { getSortList, findParentValues, formattingSortData, getDescriptionStr } =
  useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()
const { openAlert } = useMessageAlertStore()

onMounted(() => {
  getRolesList()
  selectVisibleChangeHandler(true)
})

// 经过筛选后的分类树形列表
const sortTree = ref<SortTreeItf[]>([])
// 下拉框显示回调函数
const selectVisibleChangeHandler = (visible: boolean) => {
  if (!visible) return
  if (originData.value.length === 0) getSortList()
  sortTree.value = formattingSortData(originData.value, null, 'role')
}

const total = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getRolesList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getRolesList()
}

// 角色分类id，包含所有上级分类id
const queryRoleSortId = ref<string[]>([])
// 查询是否是默认角色
const queryDefaultRole = ref<0 | 1>(null)
// 查询角色名称
const queryRoleName = ref<string>('')

// 查询到的角色列表
const queryRoleList = ref<RoleItf[]>([])
// 获取角色列表
const getRolesList = async () => {
  let sortId = ''
  const q = queryRoleSortId.value
  if (q && q.length > 0) sortId = q[q.length - 1]

  const obj = {
    sortId: sortId,
    isDefault: queryDefaultRole.value,
    realName: queryRoleName.value,
  }
  const res = await getRolesListApi(pageNum.value, pageSize.value, obj)
  if (res.code !== 200) return openAlert.error(res.message)
  queryRoleList.value = res.data.records
  total.value = res.data.total
}

// 当前角色id
const currentRoleId = ref<string>('')
// 角色名称
const roleName = ref<string>('')
// 角色名称
const roleRealName = ref<string>('')
// 角色描述
const roleDesc = ref<string>('')
// 角色是否为用户默认角色
const roleIsDefault = ref<0 | 1>(1)
// 创建，修改角色时的分类id
const tempRoleSortId = ref<string[]>([])

// 创建角色对话框
const createRoleDialogVisible = ref(false)
// 修改角色对话框
const updateRoleDialogVisible = ref(false)

const openCreateRoleDialog = () => {
  createRoleDialogVisible.value = true
}
const openUpdateRoleDialog = (
  id: string,
  name: string,
  realName: string,
  desc: string,
  sortId: string,
  isDefault: 0 | 1
) => {
  currentRoleId.value = id
  roleName.value = name
  roleRealName.value = realName
  roleDesc.value = desc
  tempRoleSortId.value = findParentValues(sortTree.value, sortId)
  roleIsDefault.value = isDefault
  updateRoleDialogVisible.value = true
}
const closeRoleDialog = () => {
  createRoleDialogVisible.value = false
  updateRoleDialogVisible.value = false
  roleName.value = ''
  roleRealName.value = ''
  roleDesc.value = ''
  roleIsDefault.value = 1
  currentRoleId.value = ''
  tempRoleSortId.value = []
}
const createDialogConfirmHandler = () => {
  createRole()
  closeRoleDialog()
}
const updateDialogConfirmHandler = () => {
  updateRole()
  closeRoleDialog()
}

// 创建角色
const createRole = async () => {
  let sortId = ''
  const t = tempRoleSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setRoleApi({
    name: roleName.value,
    realName: roleRealName.value,
    description: roleDesc.value,
    sortId: sortId,
    isDefault: roleIsDefault.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('角色创建成功！')
  getRolesList()
}

// 修改角色信息
const updateRole = async () => {
  let sortId = ''
  const t = tempRoleSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setRoleApi({
    name: roleName.value,
    realName: roleRealName.value,
    description: roleDesc.value,
    sortId: sortId,
    isDefault: roleIsDefault.value,
    id: currentRoleId.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('角色修改成功！')
  getRolesList()
}

// 多选角色选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: RoleItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 批量删除角色
const deleteRoles = async (ids: string[]) => {
  const res = await deleteRolesApi(ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限删除成功！')
  getRolesList()
}

// 批量更新角色状态
const updateRolesStatus = async (ids: string[], status: 0 | 1) => {
  const res = await updateRolesStatusApi(ids, status)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('权限状态更新成功！')
  getRolesList()
}

// 正在进行设置的角色
const settingRole = ref<RoleItf>(null)
// 设置角色权限弹窗
const setRolePermissionsDialogVisible = ref<boolean>(false)
// 设置角色路由弹窗
const setRoleRoutesDialogVisible = ref<boolean>(false)
// 设置角色用户弹窗
const setRoleUsersDialogVisible = ref<boolean>(false)

const openRolePermissionsDialogHandldr = (role: RoleItf) => {
  settingRole.value = role
  setRolePermissionsDialogVisible.value = true
}
const openRoleRoutesDialogHandldr = (role: RoleItf) => {
  settingRole.value = role
  setRoleRoutesDialogVisible.value = true
}
const openRoleUsersDialogHandldr = (role: RoleItf) => {
  if (role.isDefault === 0) return openAlert.warning('默认角色无法设置用户')
  settingRole.value = role
  setRoleUsersDialogVisible.value = true
}

const closeRoleDialogHandldr = () => {
  settingRole.value = null
  setRolePermissionsDialogVisible.value = false
  setRoleRoutesDialogVisible.value = false
  setRoleUsersDialogVisible.value = false
}
</script>

<style lang="less" scoped>
.tips {
  font-size: 14px;
  font-weight: bold;
  color: #918f8f;
  padding: 10px 10px;
}
</style>
